package com.zhanghe.study.design_pattern.singleton_pattern.lazy;

/**
 * 双重检查锁定
 * @Author: zhanghe
 * @Date: 2020/4/21 18:27
 */
public class VolatileSingleton {
    // volatile保证原子性
    private static volatile VolatileSingleton instance = null;

    private VolatileSingleton() {

    }

    public static VolatileSingleton newInstance() {
        // 在需要的时候进行创建，如果已存在，直接返回之前的对象
        if (instance == null) {
            synchronized (VolatileSingleton.class) {
                if (instance == null) {
                    instance = new VolatileSingleton();
                    System.out.println("创建单例实例1");
                }
                System.out.println("创建单例实例2");
            }
        }
        return instance;
    }
}
